package com.itheima.business.service.impl;

import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itheima.business.config.SecretProperties;
import com.itheima.business.domain.dto.UserLoginDto;
import com.itheima.business.domain.po.SysUser;
import com.itheima.business.domain.vo.UserLoginVo;
import com.itheima.business.mapper.SysUserMapper;
import com.itheima.business.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 系统用户表 服务实现类
 * </p>
 *
 * @author shenkunlin
 * @since 2025-08-02
 */
@RequiredArgsConstructor
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {


    private final SecretProperties secretProperties;

    @Override
    public UserLoginVo login(UserLoginDto userLoginDto) {
        //1、根据账号获取用户信息
        SysUser sysUser = getBaseMapper().selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getAccount, userLoginDto.getUsername()));

        //2、密码匹配
        if(sysUser!=null && userLoginDto.getPassword().equals(sysUser.getPassword())){
            //3、令牌生成
            Map<String,Object> dataMap = new HashMap<>();
            dataMap.put("id",sysUser.getId());
            dataMap.put("username",sysUser.getAccount());
            dataMap.put("name",sysUser.getName());
            String token = JWTUtil.createToken(dataMap, secretProperties.getJwtBytes());

            //4、响应数据封装
            UserLoginVo vo = new UserLoginVo();
            vo.setId(sysUser.getId());
            vo.setName(sysUser.getName());
            vo.setUsername(sysUser.getAccount());
            vo.setToken(token);
            return vo;
        }
        return null;
    }
}
